import { Article, Comment } from '../models/index.js'

// 获取文章列表
export const getArticles = async (req, res) => {
  try {
    const { category, tag } = req.query
    const where = {}
    if (category) where.category = category
    if (tag) where.tags = { [Article.sequelize.Op.like]: `%${tag}%` }
    
    const articles = await Article.findAll({ 
      where, 
      order: [['createdAt', 'DESC']] 
    })
    
    res.json({
      success: true,
      message: '获取文章列表成功',
      data: articles
    })
  } catch (error) {
    console.error('获取文章列表失败:', error)
    res.status(500).json({ 
      success: false,
      message: '获取文章列表失败' 
    })
  }
}

// 获取单篇文章
export const getArticleById = async (req, res) => {
  try {
    const article = await Article.findByPk(req.params.id)
    if (!article) {
      return res.status(404).json({ 
        success: false,
        message: '文章不存在' 
      })
    }
    
    res.json({
      success: true,
      message: '获取文章成功',
      data: article
    })
  } catch (error) {
    console.error('获取文章失败:', error)
    res.status(500).json({ 
      success: false,
      message: '获取文章失败' 
    })
  }
}

// 新增文章
export const createArticle = async (req, res) => {
  const username = req.user?.username
  if (!username) {
    return res.status(401).json({ message: '未登录' })
  }
  
  // 允许admin和jinxuebin用户发表文章
  const allowedUsers = ['admin', 'jinxuebin']
  if (!allowedUsers.includes(username)) {
    return res.status(403).json({ message: '权限不足，无法发表文章' })
  }
  
  const { title, content, category, tags, coverImage, excerpt } = req.body
  
  if (!title || !content) {
    return res.status(400).json({ message: '标题和内容不能为空' })
  }
  
  try {
    const article = await Article.create({ 
      title, 
      content, 
      category, 
      tags, 
      coverImage,
      excerpt,
      author: username
    })
    res.status(201).json({
      success: true,
      message: '文章发表成功',
      data: article
    })
  } catch (error) {
    console.error('创建文章失败:', error)
    res.status(500).json({ message: '发表失败，请重试' })
  }
}

// 更新文章
export const updateArticle = async (req, res) => {
  const username = req.user?.username
  if (!username) {
    return res.status(401).json({ message: '未登录' })
  }
  
  // 允许admin和jinxuebin用户编辑文章
  const allowedUsers = ['admin', 'jinxuebin']
  if (!allowedUsers.includes(username)) {
    return res.status(403).json({ message: '权限不足，无法编辑文章' })
  }
  
  const { title, content, category, tags, coverImage, excerpt } = req.body
  const article = await Article.findByPk(req.params.id)
  if (!article) return res.status(404).json({ message: '文章不存在' })
  
  try {
    await article.update({ title, content, category, tags, coverImage, excerpt })
    res.json({
      success: true,
      message: '文章更新成功',
      data: article
    })
  } catch (error) {
    console.error('更新文章失败:', error)
    res.status(500).json({ message: '更新失败，请重试' })
  }
}

// 删除文章
export const deleteArticle = async (req, res) => {
  const username = req.user?.username
  if (!username) {
    return res.status(401).json({ message: '未登录' })
  }
  
  // 允许admin和jinxuebin用户删除文章
  const allowedUsers = ['admin', 'jinxuebin']
  if (!allowedUsers.includes(username)) {
    return res.status(403).json({ message: '权限不足，无法删除文章' })
  }
  
  const article = await Article.findByPk(req.params.id)
  if (!article) return res.status(404).json({ message: '文章不存在' })
  
  try {
    await article.destroy()
    res.json({ 
      success: true,
      message: '文章删除成功' 
    })
  } catch (error) {
    console.error('删除文章失败:', error)
    res.status(500).json({ message: '删除失败，请重试' })
  }
}

export const getMyArticles = async (req, res) => {
  const username = req.user?.username
  if (!username) return res.status(401).json({ message: '未登录' })
  const articles = await Article.findAll({ where: { author: username }, order: [['createdAt', 'DESC']] })
  res.json(articles)
}

// 获取某篇文章的评论
export const getComments = async (req, res) => {
  const articleId = req.params.id
  const comments = await Comment.findAll({
    where: { articleId },
    order: [['createdAt', 'ASC']]
  })
  res.json(comments)
}

// 添加评论
export const addComment = async (req, res) => {
  const username = req.user?.username
  if (!username) {
    return res.status(401).json({ message: '未登录' })
  }
  
  const articleId = req.params.id
  const { content } = req.body
  if (!content) return res.status(400).json({ message: '评论内容不能为空' })
  
  try {
    const comment = await Comment.create({ articleId, author: username, content })
    res.status(201).json({
      success: true,
      message: '评论发表成功',
      data: comment
    })
  } catch (error) {
    console.error('创建评论失败:', error)
    res.status(500).json({ message: '评论发表失败，请重试' })
  }
}

// 批量为老文章补充默认封面
export const patchDefaultCovers = async (req, res) => {
  // 只允许超级管理员操作
  const username = req.user?.username
  if (!username) {
    return res.status(401).json({ message: '未登录' })
  }
  
  const allowedUsers = ['admin', 'jinxuebin']
  if (!allowedUsers.includes(username)) {
    return res.status(403).json({ message: '权限不足，无法批量补封面' })
  }
  
  try {
    const articles = await Article.findAll({ where: { [Article.sequelize.Op.or]: [
      { coverImage: null },
      { coverImage: '' },
      { coverImage: { [Article.sequelize.Op.is]: null } }
    ] } })
    let count = 0
    for (const article of articles) {
      const defaultCover = `https://picsum.photos/800/400?random=${article.id}`
      await article.update({ coverImage: defaultCover })
      count++
    }
    res.json({ 
      success: true,
      message: `已为${count}篇老文章补充默认封面` 
    })
  } catch (error) {
    console.error('批量补封面失败:', error)
    res.status(500).json({ message: '批量补封面失败，请重试' })
  }
}

